package com.sky.module.security;

import com.sky.module.security.filter.CheckTokenFilter;
import com.sky.module.security.handler.AnonymousAuthenticationHandler;
import com.sky.module.security.handler.CustomerAccessDeniedHandler;
import com.sky.module.security.handler.LoginFailureHandler;
import com.sky.module.security.handler.LoginSuccessHandler;
import com.sky.module.security.service.CustomUseDetailService;
import com.sky.module.suppot.file.s3.OssProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;
import java.util.HashMap;

/***
 * @description 配置类
 * @param null
 * @return
 * @date 2023/2/20 10:27
 *
 */
@Configuration
@EnableWebSecurity
// 开启权限注解
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SpringSecuriyConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private LoginSuccessHandler loginSuccessHandler;

    @Resource
    private LoginFailureHandler loginFailureHandler;

    @Resource
    private AnonymousAuthenticationHandler anonymousAuthenticationHandler;
    @Resource
    private CustomerAccessDeniedHandler customerAccessDeniedHandler;

    @Resource
    private CustomUseDetailService customUseDetailService;

    @Resource

    private CheckTokenFilter checkTokenFilter;

    @Resource
    private OssProperties ossProperties;

    /***
     * @description 注入加密类
     *
     * @return org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
     * @date 2023/2/20 10:43
     *
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    protected SpringSecuriyConfig() {
        super();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
//        web.ignoring().antMatchers("/sky/**");
    }

    /***
     * @description 处理登录认证
     * @param http
     * @return void
     * @date 2023/2/20 10:30
     *
     */


    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        在登录之前进行过滤 TODO 一定登录之前加入
        http.addFilterBefore(checkTokenFilter, UsernamePasswordAuthenticationFilter.class);
        http.formLogin()  // 表单认证
                .loginProcessingUrl("/api/user/login")  // 登录请求url地址，自定义
                .successHandler(loginSuccessHandler) // 登录认证处理器
                .failureHandler(loginFailureHandler)  // 登录失败处理器
                .usernameParameter("username")     // 表示前端的表单数据 就要是username，这里是自定义重写
                .and()
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)  // 不创建session
                .and()
                .authorizeRequests() // 设置需要拦截的路径
                // 允许本地文件访问
//        "/" + ossProperties.getBucketName() + "/*"
//                .antMatchers("/" + "sky").permitAll()
//                    TOOD 减少配置减少securit 减少securit 的配合


                .antMatchers("/api/user/login", "/sky/**", "/test/**").permitAll()
                // 登录接口放行


                .anyRequest().authenticated()   // 任何请求都要认证

                .and()
                .exceptionHandling()
                .authenticationEntryPoint(anonymousAuthenticationHandler)  // 匿名无权限访问
                .accessDeniedHandler(customerAccessDeniedHandler)   // 认证用户无权限访问
                .and()
                .cors();              // 开启跨域请求
    }

    /***
     * @description 配置认证处理器
     * @param
     * @return void
     * @date 2023/2/20 10:29
     *
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 自定义一个Userdetailservice 用户的数据从这里查询
        auth.userDetailsService(customUseDetailService).passwordEncoder(passwordEncoder());
//        super.configure(auth);
    }


}
